package com.zenithmind.common.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.zenithmind.common.handler.TenantLineHandler;
import com.zenithmind.common.interceptor.TenantContextInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 多租户配置类
 * 
 * @author ZenithMind
 * @since 2024-06-30
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "zenithmind.multi-tenant.enabled", havingValue = "true", matchIfMissing = true)
public class MultiTenantConfig implements WebMvcConfigurer {

    /**
     * 租户上下文拦截器
     */
    @Bean
    public TenantContextInterceptor tenantContextInterceptor() {
        return new TenantContextInterceptor();
    }

    /**
     * 租户处理器
     */
    @Bean
    public TenantLineHandler tenantLineHandler() {
        return new TenantLineHandler();
    }

    /**
     * MyBatis-Plus 多租户插件
     */
    @Bean
    public MybatisPlusInterceptor tenantMybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        
        // 添加多租户插件
        TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor();
        tenantInterceptor.setTenantLineHandler(tenantLineHandler());
        interceptor.addInnerInterceptor(tenantInterceptor);
        
        log.info("多租户插件已启用");
        return interceptor;
    }

    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tenantContextInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(
                    "/error",
                    "/favicon.ico",
                    "/v3/api-docs/**",
                    "/swagger-ui/**",
                    "/swagger-ui.html",
                    "/doc.html",
                    "/webjars/**",
                    "/knife4j/**",
                    "/actuator/**"
                );
        log.info("租户上下文拦截器已注册");
    }
}
